var webform = liwe.module ( "webform" );

webform._dests = null;
webform._dest_div = null;

webform.init = function () { webform.load_templates (); };


webform.dynamic_form = function ( form_name, dest_div, err_cback, vals, cback )
{
	if ( typeof ( vals ) == 'undefined' ) vals ={};
	to_dict ( vals );
	webform.ajax ( { action: "webform.ajax.get_form_fields", fname: form_name } , function ( data )
	{
		var fields = list ( data.get ( 'ffields', [] ) );

		if ( fields.count () < 1 )	
		{
			if ( err_cback ) err_cback ();
			return;
		}
		var frm_tpl = webform._get_form_tpl ( data );

		var fname = fields[0] [ 'name' ];
		var f = new liwe.form5.instance ( fname );
		f.action = "webform.ajax.send_form";
		fields.iterate ( function ( item )
		{
			var args = to_dict ( item.args )
			if ( item.field == 'hidden' )
			{
				f.add ( 'hidden' , args.name, args );
			} else {
				if ( ! args [ 'value' ] ) args [ 'value' ] = vals.get ( args.name );
				f.add ( item.field, args.name ,  args );
			}
		} );
		f.addEventListener ( "complete", function ( evt )
		{
			alert ( "Messaggio inviato" );
		} );
	
		f.addEventListener ( "render", function ( evt )
		{
			if ( cback ) cback ();
		} );
		f.set ( dest_div, frm_tpl )
		//webform.dispatchEvent ( 'render_form', null, { frm_obj : f, frm_tpl : frm_tpl, frm_dest_div : dest_div, fname : form_name } );
	} );
};


webform._get_form_tpl = function ( data )
{
	var form = dict ( data.get ( 'form' ) );
	if ( form.get ( 'tpl' ) ) return webform.templates [ form.get ( "tpl_name" ) ] ;
	var tpl = new String.buffer();
	tpl.add ( webform.templates [ 'FORM_START' ] );
	var fields = list ( data.get ( 'ffields', [] ) );
	fields.iterate ( function ( item )
	{
		var args = to_dict ( item.args )
		if ( item.field == 'hidden' )
		{
			tpl.add ( "%(" +  args [ 'name' ] + ")s");
		} else {
			args [ '_label' ] = "%(" + args [ 'name' ] + "-label)s";
			args [ '_name' ] = "%(" + args [ 'name' ] + ")s";
			tpl.add ( String.formatDict ( webform.templates [ 'FORM_FIELD' ] , args ) );
		}
	} );
	tpl.add ( webform.templates [ 'FORM_END' ] );
	return tpl.toString() ;
};


webform.plugin = function ( div, params )
{
	webform.load_templates ( function ()
	{
		div.id = "plugin:webform:" + params [ 'name' ];
		webform.dynamic_form ( params [ 'name' ], div.id, function ()
		{
			div.style.display = 'none' 
			console.error ( 'webform.plugin: webform %s doesn\'t exists!', params [ 'name' ] );
		} );
	} );
};



